import React, { forwardRef,useState ,useEffect} from 'react'
import { Form, Input, Select } from 'antd'
const { Option } = Select;


const UserForm = forwardRef((props, ref) => {
  const [isDisable, setisDisable] = useState(false)
  const { roleId,region} = JSON.parse(localStorage.getItem('token'))

  const roleObj = {
    "1": 'superadmin',
    "2": 'admin',
    "3":'editor'
  }
  
  //监听props.isUpdateDisabled的值，即从父组件中传过来的值，如果有变化，更新isDisable的数据
  useEffect(() => {
    setisDisable(props.isUpdateDisabled)
  },[props.isUpdateDisabled])

  const { regionList, roleList,isUpdate } = props

  //控制区域选项是被禁用
  const checkRegionDisable = (item) => {
    //判断是新增还是更新
    if (isUpdate) {
      if (roleObj[roleId] === 'superadmin') {
        return false //说明不禁用任何选项
      } else {
        return true
      }
    } else {
      if (roleObj[roleId] === 'superadmin') {
        return false //说明不禁用任何选项
      } else {
        return item.value!==region
      }
    }
  }
 
  //控制角色选项是被禁用
  const checkRoleDisable = (item) => {
    //判断是新增还是更新
    if (isUpdate) {
      if (roleObj[roleId] === 'superadmin') {
        return false //说明不禁用任何选项
      } else {
        return true
      }
    } else {
      if (roleObj[roleId] === 'superadmin') {
        return false //说明不禁用任何选项
      } else {
        return roleObj[item.id]!=='editor'
      }
    }
    
  }

  return (
    <Form
      ref={ref}
        layout="vertical">
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名!' }]}>
          <Input />
        </Form.Item>
          <Form.Item name="password"  label="密码"
            rules={[{ required: true, message: '请输入密码!' }]}>
          <Input  type="password" />
        </Form.Item>
        <Form.Item name="region" label="区域"
            rules={isDisable?[]:[{ required: true, message: '请选择区域!'}]}>
          <Select disabled={isDisable}>
            {
              regionList.map(item => 
                <Option key={item.value} value={item.value} disabled={checkRegionDisable(item)}>{ item.title}</Option>
              )
            }
          </Select>
          </Form.Item>
          <Form.Item name="roleId" label="角色"
            rules={[{ required: true, message: '请选择角色!' }]}>
        <Select onChange={(val) => {
            if (val === 1) {
              setisDisable(true) 
              ref.current.setFieldsValue({
                region:''
              })
            } else {
              setisDisable(false)
            }
            }}>
              {
                roleList.map(item => 
                  <Option key={item.id} value={item.id} disabled={checkRoleDisable(item)}>{ item.roleName}</Option>
                )
              }
          </Select>
        </Form.Item>
      </Form>
  )
})

export default UserForm